package com.expressway.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.expressway.common.lang.Result;
import com.expressway.entity.User;
import com.expressway.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2021-04-18
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
 /**
  * 获取用户列表
  * */
    @GetMapping("/users")
    public Result users(Integer currentPage) {
        if(currentPage == null || currentPage < 1) currentPage = 1;
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(currentPage, 5);
        IPage pageData = userService.page(page, new QueryWrapper<User>().orderByAsc("id"));
        return Result.succ(pageData);
    }
    @GetMapping("/{id}")
    public Result test(@PathVariable("id") Long id) {

        return Result.succ(userService.getById(id));
    }
    /**
     * 根据名称搜索用户
     * @param
     * @return
     */
    @GetMapping("/search/{name}")
    public Result search(@PathVariable("name") String name) {
        return Result.succ( userService.list(new QueryWrapper<User>().like("username",name)))  ;

    }
    /**
     * 添加用户
     * */
    @PostMapping("/save")
    public Result saveUser(User user) {
//        User user = new User();
//        user.setUsername(username).setPassword(password).setEmail(email);
        System.out.println(user);
        return Result.succ(201,"添加成功",userService.save(user));

    }
    /**
     * 修改用户状态
     * */

    @PostMapping("/{id}/status/{userstatus}")
    public Result saveUserstatus(@PathVariable Integer id,@PathVariable Boolean userstatus) {

        if(userService.saveOrUpdate( userService.getById(id).setUserstatus(userstatus))){
            return Result.succ(null);
        }
        return Result.fail(null);

    }

    /**
     * 修改用户
     * */
    @PostMapping("/update")
    public Result updateUser(User user) {
//        System.out.println(user);

        return Result.succ(200,"修改成功",userService.updateById(user));

    }
    /**
     * 根据id删除用户
     * */
    @PostMapping("/delete/{id}")
    public Result deleteUser(@PathVariable("id") Integer id) {
//        System.out.println(user);
    if(userService.removeById(id))
        return Result.succ(200,"删除成功",true);
    else
        return Result.fail("删除失败");

    }


}
